import re

from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from app.models import FMUser, MailingAddress
from app.models.fm_user import USER_TYPE_SALES, USER_TYPE_USER
from app.models.invitation_code import InvitationCode

phone_no_re = re.compile(r'[0-9]{11}')


# 用户名、密码、邮箱、姓名、身份证、经纬度、区域、店名、店地址、照片、短信验证码
class RegisterSerializer(serializers.Serializer):
    username = serializers.CharField(
        max_length=11,
        min_length=11,
        required=True,
    )
    email = serializers.EmailField(required=False)
    password = serializers.CharField(write_only=True, min_length=8, max_length=32)
    realname = serializers.CharField(max_length=30, required=False)
    # idcard = serializers.CharField(max_length=18, required=False)
    # longitude = serializers.FloatField()  # 经度
    # latitude = serializers.FloatField()  # 纬度
    merchant_name = serializers.CharField(max_length=30)  # 商户名称
    province = serializers.IntegerField()
    city = serializers.IntegerField()
    area = serializers.IntegerField()
    address = serializers.CharField()
    user_type = serializers.IntegerField(min_value=USER_TYPE_SALES, max_value=USER_TYPE_USER, required=False)
    # sales = serializers.PrimaryKeyRelatedField(queryset=FMUser.objects.filter(user_type=USER_TYPE_SALES),
    #                                            required=False)
    code = serializers.CharField(max_length=15)
    sms_code = serializers.CharField(required=False)  # 短信验证码

    # sms_code = serializers.CharField(max_length=6, min_length=6)  # 短信验证码

    def validate_code(self, code):
        try:
            if InvitationCode.objects.get(code=code):
                return code
        except InvitationCode.DoesNotExist:
            raise ValidationError(detail=u'邀请码不存在')
        raise ValidationError(detail=u'未知错误')

    def validate_username(self, username):
        if not phone_no_re.match(username):
            raise ValidationError(detail=u'手机号格式不正确')
        try:
            FMUser.objects.get(username=username)
            raise serializers.ValidationError(detail=u'手机号已经存在')
        except FMUser.DoesNotExist:
            return username

    def validate_email(self, email):
        try:
            FMUser.objects.get(email=email)  # 邮箱已被注册
            raise serializers.ValidationError(
                _("A user is already registered with this e-mail address."))
        except FMUser.DoesNotExist:  # 邮箱未注册
            return email

    def validate_password(self, password):
        return password

    def validate_province(self, province):
        if province != 32:
            raise ValidationError(detail=u'目前只支持江苏省')
        return province

    def validate_city(self, city):
        if city != 3201:
            raise ValidationError(detail=u'目前只支持南京市')
        return city

    def validate_area(self, area):
        if 320101 <= area <= 320118:
            return area
        raise ValidationError(detail=u'区号错误')

    def validate_sales(self, sales):
        return sales

    # def validate_sms_code(self, sms_code):
    #     if sms_code == '888888':
    #         return sms_code
    #     raise ValidationError(detail=u'短信验证码错误')

    def get_cleaned_data(self):
        user_type = self.validated_data.get('user_type', USER_TYPE_USER)
        code = self.validated_data.get('code', None)
        if user_type == USER_TYPE_USER and not code:
            raise ValidationError(detail=u'邀请码不能为空')

        return {
            'username': self.validated_data.get('username', ''),
            'email': self.validated_data.get('email', ''),
            'realname': self.validated_data.get('realname', ''),
            'merchant_name': self.validated_data.get('merchant_name', ''),
            'province': self.validated_data.get('province', 32),
            'city': self.validated_data.get('city', 3201),
            'area': self.validated_data.get('area', 320101),
            'address': self.validated_data.get('address', ''),
            'user_type': self.validated_data.get('user_type', USER_TYPE_USER),
            'code': code
        }

    def create_default_address(self, user: FMUser):
        return MailingAddress.objects.create(province=self.validated_data.get('province', 32),
                                             city=self.validated_data.get('city', 3201),
                                             area=self.validated_data.get('area', 320101),
                                             addressee=user.realname,
                                             address=user.address,
                                             phone=user.username,
                                             user=user,
                                             is_default=True)

    def save(self, request):
        cleaned_data = self.get_cleaned_data()
        code = cleaned_data['code']
        del(cleaned_data['code'])
        user = FMUser(**cleaned_data)
        user.set_password(self.validated_data.get('password', ''))
        user.sales = InvitationCode.objects.get(code=code).sales
        user.save()
        self.create_default_address(user)
        return user
